package com.ruleengine.parser.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Element;

import com.ruleengine.parser.ITaskContants;
import com.ruleengine.parser.ITaskParser;
import com.ruleengine.parser.exception.RuleEngineParserException;
import com.ruleengine.task.condition.ConditionFactory;
import com.ruleengine.task.condition.ICondition;
import com.ruleengine.task.config.TaskConfigManager;
import com.ruleengine.task.impl.WhenTask;

public class WhenTaskParser extends BaseTaskParser<WhenTask> {
    private static Logger logger = Logger.getLogger(WhenTaskParser.class);

    public WhenTask parseTask(Element ele, WhenTask task)
            throws RuleEngineParserException {
        // TODO Auto-generated method stub
        // 解析条件节点
        Element eleCondition = ele.element(ITaskContants.ELE_TAG_CONDITION);
        if(eleCondition != null){
            //otherwise节点没有condition子节点
            String expr = eleCondition.element(ITaskContants.ELE_TAG_EXPRESSION).getText();
            ICondition condition = ConditionFactory.getInstance().createCondition(
                    expr);
            task.setCondition(condition);
        }

        // 解析条件节点对应的工作流节点
        List<Element> children = ele.elements();
        for (Element child : children) {
            if (!TaskConfigManager.getInstance().isWorkflowElement(
                    child.getName()))
                // 节点不是工作流节点
                continue;
            
            // 解析子工作流节点
            ITaskParser parser = TaskConfigManager.getInstance().getTaskParser(
                    child.getName());
            task.addSubTask(parser.parse(child));
        }
        return task;
    }

}
